<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Article;
/**
 * easywechat 插件
 * 用于微信各种接口开发
 */
class Weixinload extends Controller{
	// 永久素材
	protected $material;
	// 临时素材
	protected $temporary;
	// 群发实例
	protected $broadcast;
	// 用户实例
	protected $userService;
	// 菜单实例
	protected $menu;
	// 支付实例
	protected $payment;

	// 初始化操作
	public function _initialize()
	{
		// 获取配置信息
		$config = Db::name('weixin')->where('status',1)->field('appid,appsecret,mchid,mchkey,status')->find();

		$options = [
		    'debug'  => true,
		    'app_id' => $config['appid'],
		    'secret' => $config['appsecret'],
		    'token'  => 'yuqingyong',
		    // 'aes_key' => null, // 可选
		    'log' => [
		        'level' => 'debug',
		        'file'  => './material.log',
		    ],
		];
		$app = new Application($options);

		$this->material   = $app->material;
		$this->temporary  = $app->material_temporary;
		$this->broadcast  = $app->broadcast;
		$this->userService= $app->user;
		$this->menu = $app->menu;
		$this->payment = $app->payment;
	}

	// 永久素材列表
	public function material_list(Request $request)
	{
		// 素材类别
		$type = $this->request->param('type') ?: 'image';

		$lists = $this->material->lists($type, 0, 20);
		// $lists = ['item'=> []];
		$assign = [
			'material_list' => $lists['item'],
			'type' => $type
		];
		return $this->fetch('Wxload/material_list',$assign);
	}

	//-------------------------------------
	// 上传永久素材
	//-------------------------------------
	public function addMaterial(Request $request)
	{
		$this->view->engine->layout(false);
		if($request->isPost()){
			$type = $this->request->post('type');
			# 获取素材的路径
			$file = $request->file('material');
			if($type === 'image'){
				# 上传图片素材
				$info = $file->validate(['size'=>1024*1024,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'upload'. DS .'image');
				if($info){
			        $path = './upload/image/'.$info->getSaveName();
			        $result = $this->material->uploadImage($path);
			    }else{
			        echo $file->getError();
			    }
			}elseif ($type === 'voice') {
				# 上传声音素材
				$info = $file->validate(['size'=>1024*1024*5,'ext'=>'mp3,wma,wav,amr'])->move(ROOT_PATH . 'public' . DS . 'upload'. DS .'voice');
				if($info){
			        $path = './upload/voice/'.$info->getSaveName();
			        $result = $this->material->uploadVoice($path);
			    }else{
			        echo $file->getError();
			    }
			}elseif ($type === 'video') {
				# 上传视频素材
				$info = $file->validate(['size'=>1024*1024*5,'ext'=>'mp4'])->move(ROOT_PATH . 'public' . DS . 'upload'. DS .'video');
				if($info){
			        $path = './upload/video/'.$info->getSaveName();
			        $result = $this->material->uploadVideo($path, "视频标题", "视频描述");
			    }else{
			        echo $file->getError();
			    }
			}elseif ($type === 'thumb') {
				# 上传缩略图素材
				$info = $file->validate(['size'=>1024*1024,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'upload'. DS .'thumb');
				if($info){
			        $path = './upload/thumb/'.$info->getSaveName();
			        $result = $this->material->uploadThumb($path);
			    }else{
			        echo $file->getError();
			    }
			}
			$result = json_decode($result,true);
			if(array_key_exists('media_id',$result)){
				$this->success('上传成功,素材ID为：'.$result['media_id']);
			}else{
				$this->error('上传失败');
			}
		}
		return $this->fetch('Wxload/add_material');
	}

	// 上传图文消息 OkqeEkkDFEs7UqopRYgwMQUxWWbBu-caKCvEekDdJBs
	public function addArticle(Request $request)
	{
		$this->view->engine->layout(false);
		if($request->isPost()){
			$title   = $this->request->post('title','','htmlspecialchars');
			$author  = $this->request->post('author','','htmlspecialchars');
			$content = $this->request->post('content','','htmlspecialchars');
			# 上传
			$article = new Article([
				'title' => $title,
				'thumb_media_id' => 'OkqeEkkDFEs7UqopRYgwMZY2hl5dmWem-3AG1SGCjFY',
				'author' => $author,
				'content' => $content
			]);
			$result = $this->material->uploadArticle($article);
			dump($result);die;
		}
		return $this->fetch('Wxload/add_article');
	}

	// 删除永久素材 
	public function delMaterial()
	{
		// $mediaId = $this->request->param('mediaId');
		$mediaId = 'OkqeEkkDFEs7UqopRYgwMUSpoHRAoKlhl8RRFSdN01Y';
		if($mediaId){
			$result = $this->material->delete($mediaId);
			if($result->errcode == 0){
				return json_encode(['status'=>1,'msg'=>'删除成功']);
			}
		}else{
			return json_encode(['status'=>0,'msg'=>'请选择要删除素材']);
		}
	}

	// 群发消息给所有粉丝
	public function sendMessageToAll()
	{
		$messageType = 'image';
		$message = 'OkqeEkkDFEs7UqopRYgwMX6fEOE9vE9rPXOkvuFaBgM';
		// $this->broadcast->send($messageType, $message);

		// 别名方式
		$this->broadcast->sendText("大家好！欢迎使用 EasyWeChat。");
		// $broadcast->sendNews($mediaId);
		// $broadcast->sendVoice($mediaId);
		$this->broadcast->sendImage($mediaId);
		//视频：
		// - 群发给组用户，或者预览群发视频时 $message 为 media_id
		// - 群发给指定用户时为数组：[$media_Id, $title, $description]
		// $broadcast->sendVideo($message);
		// $broadcast->sendCard($cardId);

		// $this->broadcast->send($messageType, $message);
	}

	// 获取关注用户列表
	public function getAllUser()
	{
		$data = $this->userService->lists($nextOpenId = null);
		dump($data);die;
	}

	//-------------------------------------
	// 菜单设置
	//-------------------------------------
	public function setMenu()
	{
		$buttons = [
		    [
		        "type" => "click",
		        "name" => "今日歌曲",
		        "key"  => "V1001_TODAY_MUSIC"
		    ],
		    [
		        "name"       => "菜单",
		        "sub_button" => [
		            [
		                "type" => "view",
		                "name" => "搜索",
		                "url"  => "http://www.soso.com/"
		            ],
		            [
		                "type" => "view",
		                "name" => "视频",
		                "url"  => "http://v.qq.com/"
		            ],
		            [
		                "type" => "click",
		                "name" => "赞一下我们",
		                "key" => "V1001_GOOD"
		            ],
		        ],
		    ],
		];
		$this->menu->add($buttons);
	}

	// 按订单号退款
	// 1、交易时间超过一年的订单无法提交退款； 2、微信支付退款支持单笔交易分多次退款，多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。一笔退款失败后重新提交，要采用原来的退款单号。总退款金额不能超过用户实际支付金额
	public function refundMoney()
	{
		// $this->payment->refund(订单号，退款单号，总金额，退款金额，操作员，退款单号类型(out_trade_no/transaction_id)，退款账户(REFUND_SOURCE_UNSETTLED_FUNDS/REFUND_SOURCE_RECHARGE_FUNDS))

		# 1. 使用商户订单号退款
		$result = $this->payment->refund($orderNo, $refundNo, 100); // 总金额 100 退款 100，操作员：商户号
		// or
		$result = $this->payment->refund($orderNo, $refundNo, 100, 80); // 总金额 100， 退款 80，操作员：商户号
		// or
		$result = $this->payment->refund($orderNo, $refundNo, 100, 80, 1900000109); // 总金额 100， 退款 80，操作员：1900000109
		// or
		$result = $this->payment->refund($orderNo, $refundNo, 100, 80, 1900000109, 'out_trade_no'); // 总金额 100， 退款 80，操作员：1900000109, 退款单号：使用商户订单号退款
		// or
		$result = $this->payment->refund($orderNo, $refundNo, 100, 80, 1900000109, 'out_trade_no', 'REFUND_SOURCE_RECHARGE_FUNDS'); // 总金额 100， 退款 80，操作员：1900000109, 退款单号：使用商户订单号退款, 退款账户：可用余额退款

		# 2. 使用 TransactionId 退款
		$result = $this->payment->refundByTransactionId($transactionId, $refundNo, 100); // 总金额 100 退款 100，操作员：商户号
		// or
		$result = $this->payment->refundByTransactionId($transactionId, $refundNo, 100, 80); // 总金额 100， 退款 80，操作员：商户号
		// or
		$result = $this->payment->refundByTransactionId($transactionId, $refundNo, 100, 80, 1900000109); // 总金额 100， 退款 80，操作员：1900000109
		// or
		$result = $this->payment->refundByTransactionId($transactionId, $refundNo, 100, 80, 1900000109, 'REFUND_SOURCE_RECHARGE_FUNDS'); // 总金额 100， 退款 80，操作员：1900000109，退款账户：可用余额退款
	}

	// 查询退款状态
	public function searchRefund()
	{
		$result = $this->payment->queryRefund($outTradeNo);
		// or
		$result = $this->payment->queryRefundByTransactionId($transactionId);
		// or
		$result = $this->payment->queryRefundByRefundNo($outRefundNo);
		// or
		$result = $this->payment->queryRefundByRefundId($refundId);
	}

}